<?php

namespace app\web\controller;

use app\common\controller\Base;

use app\common\component\ErrorCode;
use app\common\component\Param;
use app\common\component\Redis;
use app\web\logic\BackendUserLogic;

class Login extends Base
{
    /**
     * 登录页面
     * @return mixed
     */
    public function login()
    {
        $this->assign('title', '缘路于此网站-登录页面');
        return $this->show();
    }

    /** 登录操作 */
    public function loginPost()
    {
        $backendUserLogic = new \app\web\logic\BackendUserLogic();
        $backendUser = $backendUserLogic->userLogin();
        $authentication = new \app\common\component\Authentication();
        $authentication->login($backendUser);
        return $this->responseSuccess();
    }

    /** 注册页面 */
    public function register()
    {
        $this->assign('title', '缘路于此网站-注册页面');
        return $this->show();
    }

    /** 注册账号 */
    public function registerPost()
    {
        $emailCodeKey = Redis::getInstance()->getRedisName(Redis::ACCESS_EMAIL_PREFIX, 3, Param::$validParams['email']);
        $cache_value = Redis::getInstance()->get($emailCodeKey);
        if (empty($cache_value) || empty(Param::$validParams['email_code']) || $cache_value != Param::$validParams['email_code']) {
            return $this->responseFail('验证码错误');
        }

        $backendUserLogic = new \app\web\logic\BackendUserLogic();
        if ($backendUserLogic->addUser()) {
            Redis::getInstance()->del($emailCodeKey);
            return $this->responseSuccess();
        } else {
            return $this->responseFail();
        }
    }

    /** 忘记密码 */
    public function forget()
    {
        $this->assign('title', '缘路于此网站-忘记密码页面');
        return $this->show();
    }

    /** 忘记密码操作 */
    public function forgetPost()
    {
        $emailCodeKey = Redis::getInstance()->getRedisName(Redis::ACCESS_EMAIL_PREFIX, 4, Param::$validParams['email']);
        $cache_value = Redis::getInstance()->get($emailCodeKey);
        if (empty($cache_value) || empty(Param::$validParams['email_code']) || $cache_value != Param::$validParams['email_code']) {
            return $this->responseFail('验证码错误');
        }

        $backendUserLogic = new \app\web\logic\BackendUserLogic();
        if ($backendUserLogic->forgetUser()) {
            Redis::getInstance()->del($emailCodeKey);
            return $this->responseSuccess();
        } else {
            return $this->responseFail();
        }
    }

    /** 登出 */
    public function logout()
    {
        $authentication = new \app\common\component\Authentication();
        $authentication->logout($this->backendUser);
        return $this->redirect('/');
    }

    /** 发送邮箱 */
    public function emailPost()
    {
        $scene_body = [
            // 注册场景
            1 => [
                'emailBody' => '<h1>您的注册验证码是: <strong>',
                'subject' => '注册账号-邮箱验证码',
                'receiveUser' => '注册用户',
                'keyMethod' => 'getRegisterEmailKey',
                'limit' => 3,
            ],
            // 忘记密码场景
            2 => [
                'emailBody' => '<h1>您的找回验证码是: <strong>',
                'subject' => '忘记密码-密码找回',
                'receiveUser' => '忘记密码用户',
                'keyMethod' => 'getForgetEmailKey',
                'limit' => 3,
            ],
        ];

        $sceneData = $scene_body[Param::$validParams['scene_type']];
        $expire = strtotime(date('Y-m-d' . ' 00:00:00')) + 86400 - time();
        $redisKey = Redis::getInstance()->getRedisName(Redis::ACCESS_EMAIL_PREFIX, Param::$validParams['scene_type'], Param::$validParams['email']);
        $alreadySendTimes = Redis::getInstance()->get($redisKey) ? : 0;
        if ($alreadySendTimes > $sceneData['limit']) {
            return $this->responseFail('邮件发送次数已经达到上限');
        }

        $emailCode = sprintf('%06d', mt_rand(0, 999999));
        $emailCodeKey = Redis::getInstance()->getRedisName(Redis::ACCESS_EMAIL_PREFIX, Param::$validParams['scene_type'] + 2, Param::$validParams['email']);
        $username = config('email.admin_email_account');
        $password = config('email.admin_email_password');
        $swiftSmtptransportObj = new \Swift_SmtpTransport('smtp.163.com', 465, 'ssl');
        $transport = $swiftSmtptransportObj->setUsername($username)->setPassword($password);
        $mailer = new \Swift_Mailer($transport);
        $message = new \Swift_Message();
        // 设置邮件主题
        $sceneData['emailBody'] .= $emailCode . ' </strong>; 请在5分钟内输入';
        $message->setSubject($sceneData['subject'])->setBody($sceneData['emailBody'], 'text/html');

//        // 创建attachment对象，content-type这个参数可以省略
//        $attachment = \Swift_Attachment::fromPath('image.jpg', 'image/jpeg')->setFilename('cool.jpg');
//        // 添加附件
//        $message->attach($attachment); // 一个一个的加上去

        // 用关联数组设置收件人地址，可以设置多个收件人
        $message->setTo([Param::$validParams['email'] => $sceneData['receiveUser']]);
        // 用关联数组设置发件人地址，可以设置多个发件人
        $message->setFrom([$username => 'lcm']);

//        // 添加抄送人
//        $message->setCc(array(
//            'Cc@qq.com' => 'Cc'
//        ));
//
//        // 添加密送人
//        $message->setBcc(array(
//            'Bcc@qq.com' => 'Bcc'
//        ));

        // 设置邮件回执
//        $message->setReadReceiptTo('receipt@163.com');

        // 发送邮件
        if ($mailer->send($message) == 1) {
            Redis::getInstance()->setex($redisKey, $expire, ++$alreadySendTimes);
            Redis::getInstance()->setex($emailCodeKey, 300, $emailCode);
            return $this->responseSuccess();
        } else {
            return $this->responseFail();
        }
    }
}
